import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userLogin, userRegister, userLogout } from '@/api/auth'
import { setToken, removeToken, getToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
    const token = ref(getToken())
    const userInfo = ref(null)

    const login = async (loginForm) => {
        try {
            const { data } = await userLogin(loginForm)
            token.value = data
            setToken(data)
            return data
        } catch (error) {
            throw new Error(error.message || '登录失败')
        }
    }

    const register = async (registerForm) => {
        try {
            const { data } = await userRegister(registerForm)
            return data
        } catch (error) {
            throw new Error(error.message || '注册失败')
        }
    }

    const logout = async () => {
        try {
            await userLogout()
            token.value = ''
            userInfo.value = null
            removeToken()
        } catch (error) {
            throw new Error(error.message || '登出失败')
        }
    }

    return {
        token,
        userInfo,
        login,
        register,
        logout
    }
})